package sort

const (
	Asc = iota
	Desc
)

/**
 * 二分查找
 * @since 2022/8/1 14:19
 * @author 李磊
 */

func BinarySearch(data []int, sortType int, target int) int {
	if len(data) == 0 {
		return -1
	}
	low := 0
	high := len(data) - 1
	return binarySearch(data, sortType, target, low, high)
}

func binarySearch(data []int, sortType int, target int, low int, high int) int {
	if low > high {
		return -1
	}

	mid := low + (high-low)/2
	if target == data[mid] {
		return mid
	}

	if compare(target, data[mid], sortType) {
		low = mid + 1
	} else {
		high = mid - 1
	}

	return binarySearch(data, sortType, target, low, high)
}

func compare(a int, b int, sortType int) bool {
	if sortType == Asc {
		return a > b
	} else {
		return a < b
	}
}
